package com.zhugang.week13.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @program algorithms
 * @description: preorder
 * @author: chanzhugang
 * @create: 2022/12/13 11:07
 */
public class Preorder {

    /**
     * 589 N叉树的前序遍历
     * https://leetcode.cn/problems/n-ary-tree-preorder-traversal/submissions/
     *
     * @param root
     * @return
     */
    List<Integer> result = new ArrayList<>();

    public List<Integer> preorder(Node root) {
        preorder_n(root);
        return result;
    }

    private void preorder_n(Node root) {
        if (root == null) {
            return;
        }
        result.add(root.val);
        for (int i = 0; i < root.children.size(); i++) {
            // 递归遍历子节点
            preorder_n(root.children.get(i));
        }
    }

    class Node {
        public int val;
        public List<Node> children;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }
}